<template>
  <div class="app-container">
    <div ref="chart" style="width: 100%; height: 500px;"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getParkingStats } from '@/api/parkmanagement/park'

export default {
  name: 'ParkingChart',
  data() {
    return {
      chartInstance: null
    }
  },
  mounted() {
    this.initChart()
    this.loadData()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    if (this.chartInstance) {
      this.chartInstance.dispose()
    }
  },
  methods: {
    initChart() {
      this.chartInstance = echarts.init(this.$refs.chart)
      // 初始化配置
      const option = {
        title: {
          text: '停车场使用统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: '停车场 {b}<br/>停车数量: {c}'
        },
        xAxis: {
          type: 'category',
          name: '停车场',
          data: []
        },
        yAxis: {
          type: 'value',
          name: '停车数量'
        },
        series: [{
          type: 'bar',
          data: [],
          itemStyle: {
            color: '#36a3eb'
          }
        }]
      }
      this.chartInstance.setOption(option)
    },
    async loadData() {
      try {
        const response = await getParkingStats()
        const chartData = response.data
        
        // 处理数据
        const xData = chartData.map(item => item.parkingId)
        const seriesData = chartData.map(item => item.totalCount)
        
        // 更新图表
        this.chartInstance.setOption({
          xAxis: { data: xData },
          series: [{ data: seriesData }]
        })
        
      } catch (error) {
        console.error('数据加载失败:', error)
        this.$modal.msgError('图表数据加载失败')
      }
    },
    handleResize() {
      this.chartInstance && this.chartInstance.resize()
    }
  }
}
</script>